#!/usr/bin/env python
# -*- coding:utf-8 -*-
# @FileName  :auth.py
# @Time      :2025/2/14 17:16
# @Author    :kk
import random
import string


from flask import Blueprint, render_template, request, jsonify, redirect, url_for, session
from jinja2 import TemplateNotFound

from blueprints.forms import RegisterForm, LoginForm
from decorators import login_required
from exts import mail, db, redis_client
from flask_mail import Message
from werkzeug.security import generate_password_hash, check_password_hash
from models import EmailCaptchaModel, UserModel

# /auth
bp = Blueprint("auth",__name__,url_prefix="/auth")

@bp.route("/index",methods=["GET","POST"])
@login_required
def index():
    return render_template("auth/index.html")
@bp.route("/login",methods=["GET","POST"])
def login():
    if request.method == "GET":
        return render_template("auth/login.html")
    else:
        # 获取用户输入的邮箱和密码
        form = LoginForm(request.form)
    if form.validate():
        email = form.email.data
        password = form.password.data
        user = UserModel.query.filter_by(email=email).first()
        if user and check_password_hash(user.password,password):
            # cookie: 登录授权
            # flask 中的session，是经过加密后存储在cookie中
            session["user_id"] = user.id
            return redirect(url_for("auth.index"))
        else:
            print("邮箱还未进行注册")
            return redirect(url_for("auth.login"))
    else:
        print(form.errors)
        return redirect(url_for("auth.login"))
@bp.route("/logout")
def logout():
    # session.pop("user_id")
    session.clear()
    return redirect(url_for("auth.index"))

@bp.route("/register",methods=["GET","POST"])
def register():
    if request.method == "GET":
        return render_template("auth/register.html")
    else:
        # 验证码
        # 表单验证: flask-wtf: wtforms
        form = RegisterForm(request.form)
        if form.validate():
            email = form.email.data
            username = form.username.data
            password = form.password.data
            password = generate_password_hash(password)
            print("密码长度:{}".format(len(password)))
            user = UserModel(email=email,username=username,password=password)
            db.session.add(user)
            db.session.commit()
            return redirect(url_for("auth.login"))
        else:
            print(form.errors)
            return redirect(url_for("auth.register"))
@bp.route("/captcha/email")
def get_email_captcha():
    # /captcha/email/<email>
    # /captcha/email?email=xxx@qq.com
    email = request.args.get("email")
    # 4/6 随机 数组，字母组合
    source = string.digits*4
    caption = random.sample(source,4)
    print(caption)
    caption = "".join(caption)
    message = Message(subject="注册验证码", recipients=[email], body=f"您的注册验证码是 : {caption}")
    mail.send(message)
    # memcached/redis
    redis_client.set(email,caption)

    # 用数据库表的方式存储
    # email_captcha = EmailCaptchaModel(email=email, captcha=caption)
    # db.session.add(email_captcha)
    # db.session.commit()

    # RESTful API
    # {code:200/400/500,message: "",data: {}}
    return jsonify({"code": 200, "message": "", "data": None})

@bp.route("/mail/test")
def mail_test():
    message = Message(subject="测试邮件",recipients=["497716195@qq.com"],body="你好，我是测试邮件")
    mail.send(message)
    return "邮件发送成功"
